package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.utils.JsonResult;
import org.apache.coyote.http11.HttpOutputBuffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RequestMapping("users")
@RestController   //@Controller + @ResponseBody
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @RequestMapping("reg")
    public JsonResult<Void> register(User user){
        userService.register(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User user = userService.login(username,password);
        session.setAttribute("uid",user.getUid());
        session.setAttribute("username",user.getUsername());
        return new JsonResult<User>(OK,user);
    }

    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUserNameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session){
        User user = userService.getUserInfoByUid(getUidFromSession(session));
        return new JsonResult<>(OK,user);
    }

    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(User user, HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUserNameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    //设置上传文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<String>();
    static{
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    /**
     * MultipartFile由springmvc提供的接口，为我们包装了获取任何文件类型的数据（任何类型的file都可以）
     * springboot整合springMvc，只需要在处理请求的方法参数列表上声明一个参数类型为MultipartFile的参数
     * springboot会自动将文件中的数据赋值给这个参数
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file){//判断文件是否为空
        if (file.isEmpty()){
            throw new FileEmptyException("文件为空！");
        }
        if (file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件大小超出限制！");
        }
        String contentType = file.getContentType();
        if (!AVATAR_TYPE.contains(contentType)) {
            throw new FileTypeException("文件类型不支持！");
        }
        String parent = session.getServletContext().getRealPath("upload");  //获取文件所在路径
        File dir = new File(parent);
        System.out.println("dir:" +dir);
        if (!dir.exists()){
            dir.mkdir();  //目录不存在，创建目录
        }
        //获取这个文件的名称，使用UUID生成一个新的字符串作为文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename:" + originalFilename);
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String fileName = UUID.randomUUID().toString().toUpperCase() + suffix;
        System.out.println("fileName:" + fileName);
        File dest = new File(dir,fileName); //在dir目录下创建一个叫fileName的空文件
        try {
            //将参数file中的数据写入到dest文件中(前提是两个文件的后缀保持一致)
            file.transferTo(dest);
        } catch (FileStateException e){
            throw new FileStateException("文件状态异常！");
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常!");
        }
        Integer uid = getUidFromSession(session);
        String username = getUserNameFromSession(session);
        //返回头像的路径只需要相对路径，即/upload/test.png
        String avatar ="/upload/" + fileName;
        userService.changeAvatar(uid,avatar,username);
        //文件路径返回给前端，用于做头像展示
        return new JsonResult<>(OK,avatar);
    }



}
